package com.itqian.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itqian.common.exception.Assert;
import com.itqian.common.exception.ResponseEnum;
import com.itqian.common.utils.ResultVOUtil;
import com.itqian.common.vo.ResultVO;
import com.itqian.seller.entity.StoreInfo;
import com.itqian.seller.mapper.StoreInfoMapper;
import com.itqian.seller.service.StoreInfoService;
import com.itqian.system.entity.AnnComment;
import com.itqian.system.entity.AnnCommentReply;
import com.itqian.system.entity.Announcement;
import com.itqian.system.entity.User;
import com.itqian.system.form.AnnUpdateForm;
import com.itqian.system.form.AnnouncementForm;
import com.itqian.system.form.ReplyForm;
import com.itqian.system.service.AnnCommentReplyService;
import com.itqian.system.service.AnnCommentService;
import com.itqian.system.service.AnnouncementService;
import com.itqian.system.service.UserService;
import com.itqian.system.vo.AnnCommentVO;
import com.itqian.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shishuqian
 * date 2022/3/26
 * time 16:49
 **/
@RestController
@RequestMapping("/admin/ann")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @Autowired
    private AnnCommentService annCommentService;

    @Autowired
    private AnnCommentReplyService annCommentReplyService;

    @Autowired
    private UserService userService;

    @Autowired
    private StoreInfoService storeInfoService;

    @Autowired
    private StoreInfoMapper storeInfoMapper;

    /**
     *
     * @author shishuqian
     * @desc   查询所有店铺信息，添加公告时会用到
     */
    @GetMapping("/allStore")
    public ResultVO getAllStore(){
        List<StoreInfo> list = storeInfoService.list();
        return ResultVOUtil.success(list);
    }


    /**
     *  添加公告
     */
    @PostMapping("/add")
    public ResultVO add(@Valid @RequestBody AnnouncementForm form){
        boolean b = announcementService.add(form);
        if (!b){
            return ResultVOUtil.fail("添加公告失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }

    /**
     *  分页查询公告，按更新时间降序
     */
    @GetMapping("/list/{page}/{size}")
    public ResultVO list(@PathVariable Integer page,@PathVariable Integer size){
        //参数非空校验
        Assert.notNull(page, ResponseEnum.PAGE_NOTNULL);
        Assert.notNull(size,ResponseEnum.SIZE_NOTNULL);

        Page<Announcement> list = announcementService.list(page, size);
        for (Announcement record : list.getRecords()) {
            if (record.getStoreId() != null){
                String store = storeInfoMapper.getStoreNameById(record.getStoreId());
                if (store != null){
                    record.setStoreName(store);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("content",list.getRecords());
        map.put("size",list.getSize());
        map.put("total",list.getTotal());

        return ResultVOUtil.success(map);
    }


    /**
     *  修改公告
     */
    @PutMapping("/update")
    public ResultVO update(@Valid @RequestBody AnnUpdateForm form){
        Announcement one = announcementService.getById(form.getAnnouncementId());
        Integer storeId = one.getStoreId();
        BeanUtils.copyProperties(form,one);
        one.setStoreId(storeId);
        boolean b = announcementService.updateById(one);
        if (!b){
            return ResultVOUtil.fail("修改公告失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }

    /**
     *  删除公告
     */
    @DeleteMapping("/delete/{id}")
    public ResultVO delete(@PathVariable Integer id){
        //参数非空校验
        Assert.notNull(id,ResponseEnum.PARAM_NOTNULL);
        boolean b = announcementService.removeById(id);
        if (!b){
            return ResultVOUtil.fail("删除公告失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }

    /**
     *  修改公告发布状态
     */
    @PutMapping("/status/{id}")
    public ResultVO status(@PathVariable Integer id){
        //参数非空校验
        Assert.notNull(id,ResponseEnum.PARAM_NOTNULL);
        Announcement announcement = announcementService.getById(id);
        if(announcement == null){
            return ResultVOUtil.fail("公告id无效失败，请重试...");
        }
        announcement.setAnnouncementStatus(!announcement.getAnnouncementStatus());
        boolean b = announcementService.updateById(announcement);
        if (!b){
            return ResultVOUtil.fail("修改公告状态失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }


    /**
     *  查看留言
     */
    @GetMapping("/getComment/{id}")
    public ResultVO get(@PathVariable Integer id){
        //校验参数非空
        Assert.notNull(id,ResponseEnum.PARAM_NOTNULL);
        //1.查询该公告的所有留言
        QueryWrapper<AnnComment> wrapper = new QueryWrapper<>();
        wrapper.eq("owner_id",id);
        wrapper.orderByDesc("date");
        List<AnnComment> list = annCommentService.list(wrapper);
        //评论列表
        List<AnnCommentVO> voList = new ArrayList<>();
        //2.查询每个留言的回复
        for (AnnComment annComment : list) {
            QueryWrapper<AnnCommentReply> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("comment_id",annComment.getId());
            wrapper1.orderByDesc("date");
            //查询留言回复
            List<AnnCommentReply> replyList = annCommentReplyService.list(wrapper1);
            AnnCommentVO annCommentVO = new AnnCommentVO();
            BeanUtils.copyProperties(annComment,annCommentVO);
            annCommentVO.setReply(replyList);
            voList.add(annCommentVO);
        }

        return ResultVOUtil.success(voList);
    }

    /**
     *  回复留言
     */
    @PostMapping("/reply")
    public ResultVO reply(@RequestHeader("token") String token,@Valid @RequestBody ReplyForm form){
        //获取回复评论的用户id
        Integer userId = TokenUtils.getUserId(token);
        User fromUser = userService.getById(userId);

        AnnCommentReply reply = new AnnCommentReply();
        reply.setFromId(userId)
                .setFromName(fromUser.getNickname())
                .setFromAvatar(fromUser.getIconUrl())
                .setToId(form.getToId())
                .setToName(form.getToName())
                .setToAvatar(form.getToAvatar())
                .setContent(form.getContent())
                .setCommentId(form.getCommentId())
                .setDate(LocalDateTime.now());

        boolean save = annCommentReplyService.save(reply);
        return ResultVOUtil.success(null);
    }

    /**
     *  删除留言
     *  type === comment 删除留言
     *  type == reply 删除对留言的回复
     */
    @DeleteMapping("/deleteComment/{type}/{id}")
    public ResultVO deleteComment(@PathVariable String type,@PathVariable Integer id){
        Assert.notBlank(type,ResponseEnum.PARAM_NOTNULL);
        Assert.notNull(id,ResponseEnum.PARAM_NOTNULL);

        if (type.equals("comment")){
            annCommentService.removeById(id);
        }else{
            annCommentReplyService.removeById(id);
        }

        return ResultVOUtil.success(null);
    }


}
